﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Easy.Common;
using System.Data.Common;
using System.Data.SqlClient;

namespace Easy.Operation
{
    public class UserPrivilege_Functions
    {
        public static string BusinessUnit_Save(BusinessUnitClass bu,string optionType,string optionUser)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_BusinessUnit_Save";
      
            SqlParameter[] param =
            { 
                new SqlParameter("@BusinessUnitId",bu.BusinessUnitId==""?null:bu.BusinessUnitId),
                new SqlParameter("@Name",bu.Name==""?null:bu.Name),
                new SqlParameter("@PreBusinessUnit", bu.PreBusinessUnit==""?null:bu.PreBusinessUnit),
                new SqlParameter("@optionType",optionType),
                new SqlParameter("@optionUser",optionUser==""?null:optionUser)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);

            return ds.Tables[0].Rows[0]["BusinessUnitId"].ToString();
            
        }

        public static string SystemUser_Save(SystemUserClass su, string optionType, string optionUser)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_SystemUser_Save";
           
            SqlParameter[] param =
            { 
                new SqlParameter("@UserId", su.UserId==""?null:su.UserId),
                new SqlParameter("@Name",su.Name==""?null:su.Name),
                new SqlParameter("@BusinessUnit",su.BusinessUnit==""?null:su.BusinessUnit),
                new SqlParameter("@optionType",optionType),
                new SqlParameter("@optionUser",optionUser==""?null:optionUser)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);

            return ds.Tables[0].Rows[0]["UserId"].ToString();
        }


        public static string Role_Save(RoleClass su, string optionType, string optionUser)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_Role_Save";
         
            SqlParameter[] param =
            { 
                new SqlParameter("@RoleId", su.RoleId==""?null:su.RoleId),
                new SqlParameter("@Name",su.Name==""?null:su.Name),
                new SqlParameter("@BusinessUnitId",su.OwningBusinessUnit==""?null:su.OwningBusinessUnit),
                new SqlParameter("@optionType",optionType),
                new SqlParameter("@optionUser",optionUser==""?null:optionUser)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);

            return ds.Tables[0].Rows[0]["RoleId"].ToString();
        }


//zw
        public static string SiteMapId_Save(Guid su, List<SiteMapClass> Sm, string optionUser)
        {
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string sql = "delete from SiteMapRoleMapRelationship where RoleMapId=@id";
            SqlParameter[] param = new SqlParameter[] { new SqlParameter("@id", su)};
            DbCommand cmd = sqlhelper.GetSqlStringCommand(sql);
            cmd.Parameters.AddRange(param);
            sqlhelper.ExecuteNonQuery(cmd);
      //       foreach (var item in Sm.ChildSiteMap)
            foreach (SiteMapClass item in Sm)
            {
                 DbCommand insert_command = new SqlCommand("insert into SiteMapRoleMapRelationship(SiteMapRoleMapRelationshipId,SiteMapId,RoleMapId)VALUES(NEWID(),@sitemapid,@roleid)");
                 SqlParameter[] insert_param = new SqlParameter[] { new SqlParameter("@sitemapid",item.SiteMapId),new SqlParameter("@roleid", su)};
                 insert_command.Parameters.AddRange(insert_param);
                 sqlhelper.ExecuteNonQuery(insert_command);
                //insert_command.ExecuteNonQuery();
            }

            return null;

        }


//zw-end
  //zw
       public static string ChangeBs(string UserId,string NewId)
        {
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);
            string isql = "select businessUnitId from SystemUser where SystemUserId=@UserId";
            SqlParameter[] iparam = new SqlParameter[] { new SqlParameter("@UserId", UserId) };
            DbCommand icmd = sqlhelper.GetSqlStringCommand(isql);
            icmd.Parameters.AddRange(iparam);
            DataTable itable = sqlhelper.ExecuteDataSet(icmd).Tables[0];
            string ClientId = itable.Rows[0]["businessUnitId"].ToString();
          
           //更新所选用户的部门Id
           
            string sql = "update SystemUser set businessUnitId=@Newid  where SystemUserId=@UserId";
            SqlParameter[] param = new SqlParameter[] { new SqlParameter("@NewId", NewId), new SqlParameter("@UserId", UserId) };
            DbCommand cmd = sqlhelper.GetSqlStringCommand(sql);
            cmd.Parameters.AddRange(param);
            sqlhelper.ExecuteNonQuery(cmd);

            //更新所选用户的子部门所有相关信息
          
            string strProcedureName = "sp_UpateOwningBusinessUnit";
            SqlParameter param_Update = new SqlParameter("@SystemUserId", UserId == "" ? null : UserId);
            DbCommand cmd_Update = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd_Update.Parameters.Add(param_Update);
            sqlhelper.ExecuteNonQuery(cmd_Update);
            int num = int.Parse((ClientId == NewId ? 0 : 1).ToString());
            if(num==0)
            {
                throw new Exception("更改的目标部门与本身部门一致");
            }
            return num.ToString();
        }
//zw-end

        //4.29迁移用户数据
        public static string isMigrateUserRecords(string SystemUserId,string ToWho){
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);
            string strProcedureName = "sp_MigrateUserRecords";
            SqlParameter[] param = 
            {
                new SqlParameter("@SystemUserId",SystemUserId==""? null : SystemUserId),  //用户ID
                new SqlParameter("@ToWho",ToWho==""? null : ToWho)                  //将记录迁移到该用户
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            int num = sqlhelper.ExecuteNonQuery(cmd);
            if (ToWho == SystemUserId)
            {
                throw new Exception("迁移的目标用户与本身用户一致");
            }
            return num.ToString();

        }
        //

        public static string UserRole_Save(UserRoleClass ur,  string optionUser)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_UserRole_Save";
           
            string roles = "";
            foreach (RoleClass role in ur.Roles)
            {
                if(role.RoleId!=""&&role.RoleId.Length==36)
                {
                    roles += role.RoleId+"|";
                }
            }
            if (roles != "")
            {
                roles = roles.Substring(0, roles.Length - 1);
            }

            SqlParameter[] param =
            { 
                new SqlParameter("@UserId", ur.UserId),
                new SqlParameter("@Roles",roles),
                new SqlParameter("@optionUser",optionUser==""?null:optionUser)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);

            return ur.UserId;
        }




        public static string RolePrivilege_Save(RolePrivilegeClass ur, string optionUser)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_RolePrivilege_Save";
     
            foreach (EntityPrivilegeClass pri in ur.EntityPrivileges)
            {
                SqlParameter[] param =
                { 
                    new SqlParameter("@roleid", ur.RoleId),
                    new SqlParameter("@entityname",pri.EntityName),
                    new SqlParameter("@read",pri.Read.ToString()),
                    new SqlParameter("@write",pri.Write.ToString()),
                    new SqlParameter("@create", pri.Create.ToString()),
                    new SqlParameter("@delete",pri.Delete.ToString()),
                    new SqlParameter("@assign",pri.Assign.ToString())
                };
                DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
                cmd.Parameters.AddRange(param);
                ds = sqlhelper.ExecuteDataSet(cmd);
            }

            return ur.RoleId;
        }

        public static string IsHaveRight(string RecordId, string UserID, string Action, string EntityName)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_get_isHaveRight";
          
            SqlParameter[] param =
            { 
                new SqlParameter("@RecordId",RecordId),
                new SqlParameter("@UserID",UserID),
                new SqlParameter("@Action",Action),
                new SqlParameter("@EntityName",EntityName)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);

            return ds.Tables[0].Rows[0]["ishaveright"].ToString(); 
        }

        public static List<RoleClass> GetRoleList()
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetRole";
          
            ds = sqlhelper.ExecuteDataSet(sqlhelper.GetStoredProcCommand(strProcedureName));
            List<RoleClass> list = new List<RoleClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                RoleClass role = new RoleClass();
                role.RoleId = item["RoleMapId"].ToString();
                role.Name = item["Name"].ToString();
                role.BusinessUnit = item["BusinessUnit"].ToString();
                role.OwningBusinessUnit = item["OwningBusinessUnit"].ToString();

                list.Add(role);
            }
            return list;
        }


        public static RoleClass GetRole(string RoleId)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetRole";
       

            SqlParameter[] param =
            { 
                new SqlParameter("@roleid",RoleId)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);


            List<RoleClass> list = new List<RoleClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                RoleClass role = new RoleClass();
                role.RoleId = item["RoleMapId"].ToString();
                role.Name = item["Name"].ToString();
                role.BusinessUnit = item["BusinessUnit"].ToString();
                role.OwningBusinessUnit = item["OwningBusinessUnit"].ToString();

                list.Add(role);
            }
            return list.Count > 0 ? list[0] : null;
        }

        public static List<EntityPrivilegeClass> GetEntityRoleList(string RoleId)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetEntityRoleList";
          
            SqlParameter[] param =
            { 
                new SqlParameter("@RoleId",RoleId)
            };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);
            List<EntityPrivilegeClass> list = new List<EntityPrivilegeClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                EntityPrivilegeClass role = new EntityPrivilegeClass();
                role.EntityId = item["EntityMapId"].ToString();
                role.EntityName = item["EntityName"].ToString();
                role.EntityDisplayName = item["EntityDisplayName"].ToString();
                role.Read = int.Parse(item["Read"].ToString());
                role.Write = int.Parse(item["Write"].ToString());
                role.Create = int.Parse(item["Create"].ToString());
                role.Delete = int.Parse(item["Delete"].ToString());
                role.Assign = int.Parse(item["Assign"].ToString());

                list.Add(role);
            }
            return list;
        }

        public static List<SystemUserClass> GetUserList()
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetUser";
    
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            ds = sqlhelper.ExecuteDataSet(cmd);
            List<SystemUserClass> list = new List<SystemUserClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                SystemUserClass user = new SystemUserClass();
                user.UserId = item["SystemUserId"].ToString();
                user.Name = item["Name"].ToString();
                user.BusinessUnitName = item["BusinessUnitName"].ToString();
                user.BusinessUnit = item["BusinessUnitId"].ToString();

                list.Add(user);
            }
            return list;
        }

        public static UserRoleClass GetRolesByUserIdList(string UserId)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetRolesByUserId";
    
            SqlParameter[] param =
                { 
                    new SqlParameter("@UserId", UserId)
                };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);
            UserRoleClass user = new UserRoleClass();
            List<RoleClass> rolelist = new List<RoleClass>();
            user.UserId = UserId;
            foreach (DataRow item in ds.Tables[0].Rows)
            {

                // List<RoleClass> role = new List<RoleClass>();

                RoleClass r = new RoleClass();
                r.RoleId = item["RoleMapId"].ToString();
                r.Name = item["RoleName"].ToString();
                //   r.BusinessUnitId = item["RoleName"].ToString();
                // user.Roles.Add(r);

                // user.Roles[0].Create = int.Parse(item["Create"].ToString());
                // user.Roles[0].Delete = int.Parse(item["Delete"].ToString());
                // user.Roles[0].Assign = int.Parse(item["Assign"].ToString());
                //user.Roles.Add(role);
                rolelist.Add(r);
            }
            user.Roles = rolelist;
            return user;
        }

        public static SystemUserClass GetUser(string UserId)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetUser";
       
            SqlParameter[] param =
                { 
                    new SqlParameter("@userid", UserId)
                };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);
            List<SystemUserClass> list = new List<SystemUserClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                SystemUserClass user = new SystemUserClass();
                user.UserId = item["SystemUserId"].ToString();
                user.Name = item["Name"].ToString();
                user.BusinessUnitName = item["BusinessUnitName"].ToString();
                user.BusinessUnit = item["BusinessUnitId"].ToString();

                list.Add(user);
            }
            return list.Count > 0 ? list[0] : null;
        }

        public static List<BusinessUnitClass> GetBusinessUnitList()
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetBusinessUnit";
            ds = sqlhelper.ExecuteDataSet(sqlhelper.GetStoredProcCommand(strProcedureName));
            List<BusinessUnitClass> list = new List<BusinessUnitClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                BusinessUnitClass bu = new BusinessUnitClass();
                bu.BusinessUnitId = item["BusinessUnitId"].ToString();
                bu.Name = item["Name"].ToString();
                bu.PreBusinessUnit = item["PreBusinessUnit"].ToString();
                bu.PreBusinessUintName = item["PreBusinessUintName"].ToString();
                list.Add(bu);
            }
            return list;


        }

        public static BusinessUnitClass GetBusinessUnit(string BusinessUnit)
        {
            DataSet ds = null;
            SqlDatabase sqlhelper = new SqlDatabase(Config.TulingBuyCrmConnectString);

            string strProcedureName = "sp_GetBusinessUnit";
         
            SqlParameter[] param =
                { 
                    new SqlParameter("@businessunitid", BusinessUnit)
                };
            DbCommand cmd = sqlhelper.GetStoredProcCommand(strProcedureName);
            cmd.Parameters.AddRange(param);
            ds = sqlhelper.ExecuteDataSet(cmd);
            List<BusinessUnitClass> list = new List<BusinessUnitClass>();


            foreach (DataRow item in ds.Tables[0].Rows)
            {
                BusinessUnitClass bu = new BusinessUnitClass();
                bu.BusinessUnitId = item["BusinessUnitId"].ToString();
                bu.Name = item["Name"].ToString();
                bu.PreBusinessUnit = item["PreBusinessUnit"].ToString();
                bu.PreBusinessUintName = item["PreBusinessUintName"].ToString();

                list.Add(bu);
            }
            return list.Count > 0 ? list[0] : null;
        }

    
    }
}